package cn.com.bluemoon.daps.sync.core.sync.compare.sql;

import cn.com.bluemoon.daps.model.entity.DapDataModelSubordinateKey;
import cn.com.bluemoon.daps.model.entity.DapDataModelTable;
import cn.com.bluemoon.daps.model.entity.DapDataModelTableField;
import cn.com.bluemoon.daps.model.entity.DapDataModelTablePartition;
import cn.com.bluemoon.daps.sync.base.BmScript;
import cn.com.bluemoon.daps.sync.base.ModifyType;
import cn.com.bluemoon.daps.sync.base.SqlCompareResult;
import cn.com.bluemoon.daps.sync.core.sync.GlobalConfig;
import cn.com.bluemoon.daps.sync.core.sync.Tuple2;
import cn.com.bluemoon.daps.sync.core.sync.compare.TableComparator;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Jarod.Kong
 * @date 2021/6/3 13:51
 */
@Slf4j
public class SqlTableComparator extends TableComparator<SqlCompareResult> {

    public SqlTableComparator(GlobalConfig globalConfig, Tuple2<DapDataModelTable> tableTuple2) {
        super(globalConfig, tableTuple2);
    }

    @Override
    public void change0(List<SqlCompareResult> sqlCollector) {
        super.change0(sqlCollector);
        BmScript sql = bmSql.changeTable(oldTable, newTable);
        sqlCollector.add(SqlCompareResult.builder()
                .modifyType(ModifyType.ALTER.table())
                .script(sql)
                .build());
    }

    @Override
    public void drop0(List<SqlCompareResult> sqlCollector) {
        // 针对模型没有而数据库有的表，目前需求是忽略数据库的表，而不进行删除表
        if (!globalConfig.isCanDropDbTable() && oldTable != null && newTable == null) {
            log.debug("开发同步中：针对模型没有而数据库有的表，目前需求是忽略数据库的表，而不进行删除表, table:{}", oldTable);
        } else {
            super.drop0(sqlCollector);
            assert oldTable != null;
            BmScript sql = bmSql.dropTable(oldTable.getEngName());
            sqlCollector.add(SqlCompareResult.builder()
                    .modifyType(ModifyType.DROP.table())
                    .script(sql)
                    .build());
        }
    }

    @Override
    public void create0(List<SqlCompareResult> sqlCollector) {
        super.create0(sqlCollector);
        // 字段有序
        List<DapDataModelTableField> newFs = getNewTFieldsOrderByFieldRank();
        List<DapDataModelSubordinateKey> newIs = getV1AndV2DbIndexes().stream().map(Tuple2::getNewT).collect(Collectors.toList());
        List<DapDataModelTablePartition> newPs = getV1AndV2DbPartitions().stream().map(Tuple2::getNewT).collect(Collectors.toList());
        BmScript sql = bmSql.createTable(newTable, newFs, newIs, newPs);
        sqlCollector.add(SqlCompareResult.builder()
                .modifyType(ModifyType.CREATE.table())
                .script(sql)
                .build());
    }
}
